package com.origin.chaos.mail;

import com.origin.chaos.common.exception.OutPutMsgException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

/**
 * @author dingtao
 */
@Service
@Slf4j
public class MailServiceImpl implements MailService {

    private JavaMailSender mailSender;

    @Value("${spring.mail.username}")
    private String from;

    @Override
    public void sendRegisterCode(String to, String code) {
        try {
            MimeMessage message = this.mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(this.from);
            helper.setTo(to);
            helper.setSubject("[像素大战] 请查看您的注册验证码");
            StringBuilder textBuilder = new StringBuilder();
            textBuilder.append("您的注册验证码为");
            textBuilder.append("</br>");
            textBuilder.append("<strong>").append(code).append("</strong>").append("验证码5分钟内有效");
            helper.setText(textBuilder.toString(), true);
            this.mailSender.send(message);
        } catch (MessagingException e) {
            e.printStackTrace();
            throw new OutPutMsgException("邮件发送失败");
        }
    }

    @Override
    public void sendResetPsdCode(String to, String code) {
        try {
            MimeMessage message = this.mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(this.from);
            helper.setTo(to);
            helper.setSubject("[像素大战] 请查看您的重置密码验证码");
            StringBuilder textBuilder = new StringBuilder();
            textBuilder.append("您的重置密码验证码为");
            textBuilder.append("</br>");
            textBuilder.append("<strong>").append(code).append("</strong>").append("验证码5分钟内有效");
            helper.setText(textBuilder.toString(), true);
            this.mailSender.send(message);
        } catch (MessagingException e) {
            e.printStackTrace();
            throw new OutPutMsgException("邮件发送失败");
        }
    }

    @Autowired
    public void setMailSender(JavaMailSender mailSender) {
        this.mailSender = mailSender;
    }

}